package samples;

// Use the Sigslot.build macro to augment the Button class with signals:
@:build(hxsigslot.SigSlot.build( {
	
	// Declare the signals:
	function Pressed() {}
	
})) class Button {
	
	var name : String;
	
	public function new( name : String ) : Void {
		this.name = name;
	}
	
	public function press() : Void {
		trace( "" );
		trace( name + " pressed" );
		dispatchPressed();
	}
	
	/* The macro added these public methods:

	public function bindPressed( listener : Void -> Void ) : Void { ... } // This binds the listener to the Pressed signal.
	public function dispatchPressed() : Void { ... } // This calls all the listener functions of the Pressed signal in the order they were bound.
	
	public function unbindPressed( listener : Void -> Void ) : Void { // This unbinds a listener
		if ( _sigslot_listenerHash == null ) return;
		var list = _sigslot_listenerHash.get("Pressed");
		if ( list == null ) return;
		list.remove(listener);
	}
	
	inline public function unbindAll() : Void { // This unbinds all listeners
		_sigslot_listenerHash = null;
	}
	*/
	
}

class Light {
	
	var state : Bool;
	var name : String;
	
	public function new( name : String ) : Void {
		this.name = name;
	}
	
	public function toggle() : Void {
		state = !state;
		printState();
	}
	
	public function turnOn() : Void {
		state = true;
		printState();
	}
	
	public function turnOff() : Void {
		state = false;
		printState();
	}
	
	private function printState() : Void {
		
		if ( state ) {
			trace( name + " is: ON" );
		}else {
			trace( name + " is: OFF" );
		}
	}
	
}

class Sample1 
{

	public static function runSample() {
		
		// Create the off on and toggle buttons:
		var offBtn = new Button( "Off button" );
		var onBtn = new Button( "On button" );
		var toggleBtn = new Button( "Toggle button" );
		
		// Create a red light:
		var redLight = new Light( "Red Light" );
		
		// Connect the butons to the respective light functions:
		offBtn.bindPressed(redLight.turnOff);
		onBtn.bindPressed(redLight.turnOn);
		toggleBtn.bindPressed(redLight.toggle);
		
		// Press the buttons and see that the light is affected by them.
		offBtn.press();
		onBtn.press();
		toggleBtn.press();
		toggleBtn.press();
		
		// We create a green light:
		var greenLight = new Light( "Green Light" );
		
		// And connect its toggle function to the toggle button.
		toggleBtn.bindPressed( greenLight.toggle );
		
		// Now the toggle button toggles both lights.
		toggleBtn.press();
		toggleBtn.press();
		
		// Disconnect the red light from the toggle button:
		toggleBtn.unbindPressed( redLight.toggle );
		
		// Now only the green light is affected:
		toggleBtn.press();
		
		toggleBtn.unbindAll();
		toggleBtn.press();
		
	}
	
}


